﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI;
using KINLO.Model.Dto;
using KINLO.Model;
using KINLO.Model.Attributes;
using System.Reflection;
using System.IO;
using System.Collections.ObjectModel;
using NPOI.SS.UserModel;
using KINLO.UI.Main.VM;
using NPOI.XSSF.UserModel;

namespace KINLO.UI.Main.Hepler
{
   public  class ExcelHelper
    {
        public static bool SaveToExcel(string filePath, ObservableCollection<WeightDto> rows)
        {
            if (!string.IsNullOrEmpty(filePath) && rows.Count > 0)
            {
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
                var ObjType= rows[0].GetType();
                var properties= ObjType.GetProperties();
                List<PropertyInfoHelper> PropertyInfos = new List<PropertyInfoHelper>();
                foreach (var property in properties)
                {
                    var customAttrs = property.GetCustomAttributes<PrintExportAttribute>();
                    foreach (var attr in customAttrs)
                    {
                        if (attr.Visibility == true)
                        {
                            PropertyInfos.Add(new PropertyInfoHelper { PropertyInfo = property, Description = attr.Description, Order = attr.Order });
                        }
                    }
                }
                if (PropertyInfos.Count > 0)
                {
                    PropertyInfos = PropertyInfos.OrderBy(s => s.Order).ToList();

                    //创建SHEET头
                    var headerRow = sheet.CreateRow(0);
                    for (var i = 0; i < PropertyInfos.Count; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(PropertyInfos[i].Description);
                    }

                    var innerCellStye1 = book.CreateCellStyle();
                    innerCellStye1.FillPattern = FillPattern.SolidForeground;
                    innerCellStye1.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;

                    var innerCellStye2 = book.CreateCellStyle();
                    innerCellStye2.FillPattern = FillPattern.SolidForeground;
                    innerCellStye2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
                    //创建SHEET体
                    for (var j=0;j<rows.Count;j++)
                    {
                        var bodyRow = sheet.CreateRow(j+1);
                        for (var i = 0; i < PropertyInfos.Count; i++)
                        {
                            var r = rows[j];
                            string val;
                            try
                            {
                                var value = PropertyInfos[i].PropertyInfo.GetValue(r);
                                if (value is DateTime)
                                {
                                    var date = (DateTime)value;
                                    val = date.ToString("yyyy-MM-dd HH:mm:ss");
                                }
                                else
                                {
                                    val = value.ToString();
                                } 
                            }
                            catch
                            {
                                val = "";
                            }
                            var cell = bodyRow.CreateCell(i);
                            if (PropertyInfos[i].Description == "判定结果")
                            {
                                int isGoods;
                                if (int.TryParse(val, out isGoods))
                                {
                                    if (isGoods >= 100)
                                    {
                                        val = "合格";
                                        cell.CellStyle = innerCellStye2;

                                    }
                                    else
                                    {
                                        val = "不合格";
                                        cell.CellStyle = innerCellStye1;
                                    }
                                }
                                else
                                {
                                    val = "NG";
                                    cell.CellStyle = innerCellStye1;
                                }

                            }
                            if (PropertyInfos[i].Description == "判定结果")
                            {
                                int isGoods;
                                if (int.TryParse(val, out isGoods))
                                {
                                    if (isGoods >= 100)
                                    {
                                        val = "合格";
                                        cell.CellStyle = innerCellStye2;

                                    }
                                    else
                                    {
                                        val = "不合格";
                                        cell.CellStyle = innerCellStye1;
                                    }
                                }
                                else
                                {
                                    val = "NG";
                                    cell.CellStyle = innerCellStye1;
                                }

                            }
                            cell.SetCellValue(val); 
                        }
                    }
                    using (var ms = new MemoryStream())
                    {
                        book.Write(ms); 
                        using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            var data = ms.ToArray();
                            fs.Write(data, 0, data.Length);
                            fs.Flush();
                        }
                        book = null;
                    }
                    return true;
                } 
                else
                {
                    throw new Exception("找不到相关的导出到Excel的属性");
                } 
            } 
            return false;
        }

        public static bool SaveToFrontAfterWeight(string filePath, List<Weight> rows, string type)
        {
             
            if (!string.IsNullOrEmpty(filePath) && rows.Count > 0)
            {
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
                var innerCellStye1 = book.CreateCellStyle();  


                //创建SHEET头
                var headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("电池条码");
                headerRow.CreateCell(1).SetCellValue(type == "Front" ? "注液前称重" : "注液后称重");
                //创建SHEET体
                for (int i = 0; i < rows.Count; i++)
                {
                    var bodyRow = sheet.CreateRow(i + 1);
                    var row = rows[i];
                    bodyRow.CreateCell(0).SetCellValue(row.BattBarCode);
                    var cell1 = bodyRow.CreateCell(1);
                    cell1.SetCellType(CellType.Numeric); 
                    if (type == "Front")
                        cell1.SetCellValue(row.FInjectionWeight.ToString());
                    else
                        cell1.SetCellValue(row.BInjectionWeight.ToString());
                }
                using (var ms = new MemoryStream())
                {
                    book.Write(ms);
                    using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        var data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
                
                return true;
            }
            else
            {
                throw new Exception("导出到Excel发生异常");
            }
        }

        /// <summary>
        /// 压力值数据导出
        /// </summary>
        /// <param name="data"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool Export(List<PressureVesselModel> data, string filePath)
        {
            try
            {
                // 创建工作簿
               IWorkbook workbook = new XSSFWorkbook(); // 使用XSSFWorkbook创建.xlsx文件，如果需要.xls文件，可以使用HSSFWorkbook

                // 创建工作表
                ISheet sheet = workbook.CreateSheet("PressureVesselData");

                // 写入表头
                var headers = typeof(PressureVesselModel).GetProperties();
                IRow headerRow = sheet.CreateRow(0);
                for (int col = 0; col < headers.Length; col++)
                {
                    string name = "";
                    switch (headers[col].Name)
                    {
                        case "TimeStamp":
                            name = "时间";
                            break;
                        case "Name": // 如果还有其他情况，例如 "Name"
                            name = "名称";
                            break;
                        case "Type": // 还可以处理其他情况，例如 "Type"
                            name = "类型";
                            break;
                        case "PressureValue": // 还可以处理其他情况，例如 "Type"
                            name = "压力值";
                            break;
                        // 添加其他情况...
                        default:
                            // 如果没有匹配的情况，可以选择设置一个默认值
                            name = headers[col].Name;
                            break;
                    }

                    headerRow.CreateCell(col).SetCellValue(name);
                }

                // 写入数据
                for (int row = 0; row < data.Count; row++)
                {
                    var item = data[row];
                    IRow dataRow = sheet.CreateRow(row + 1);
                    for (int col = 0; col < headers.Length; col++)
                    {
                        dataRow.CreateCell(col).SetCellValue(headers[col].GetValue(item).ToString());
                    }
                }

                // 保存工作簿到指定路径
                using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fs);
                }

                return true; // 成功导出
            }
            catch (Exception ex)
            {
                // 在实际应用中，您可能希望记录异常信息或采取其他操作
                return false; // 导出失败
            }
        }

        /// <summary>
        /// 压力值数据导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<PressureVesselModel> Import(string filePath)
        {
            List<PressureVesselModel> importedData = new List<PressureVesselModel>();

            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    IWorkbook workbook = new XSSFWorkbook(fs);
                    ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表

                    for (int rowIdx = 1; rowIdx <= sheet.LastRowNum; rowIdx++)
                    {
                        IRow row = sheet.GetRow(rowIdx);
                        if (row != null)
                        {
                            PressureVesselModel pressureVessel = new PressureVesselModel();
                            pressureVessel.Id = Guid.Parse(row.GetCell(0).StringCellValue);
                            pressureVessel.TimeStamp =DateTime.Parse(row.GetCell(1).StringCellValue);
                            pressureVessel.Name = row.GetCell(2).StringCellValue;
                            pressureVessel.Type = row.GetCell(3).StringCellValue;
                            pressureVessel.PressureValue =double.Parse(row.GetCell(4).StringCellValue);

                            importedData.Add(pressureVessel);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 在实际应用中，你可能希望记录异常信息或采取其他操作
                throw ex;
            }

            return importedData;
        }
    }



    public class PropertyInfoHelper
    {
        public PropertyInfo PropertyInfo { get; set; }
        public int Order { get; set; }
        public String Description { get; set; }
    }
}
